package org.example.video.controller;


import org.example.video.crontab.TranscodingJob;
import org.example.video.pojo.PageResult;
import org.example.video.pojo.Video;
import org.example.video.service.VideoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

@RestController
@RequestMapping("/api/videos")
public class VideoController {

    @Autowired
    private VideoService videoService;

    @Autowired
    private TranscodingJob transcodingJob;

    /**
     * 上传视频文件
     */
    @PostMapping("/upload")
    public ResponseEntity<Video> upload(
            @RequestPart("file") MultipartFile file,
            @RequestParam("title") String title,
            @RequestParam("desc") String desc
    ) throws Exception {
        Video video = videoService.upload(file, title, desc);
        return ResponseEntity.ok(video);
    }

    /**
     * 轮询转码任务（正式环境使用定时器）
     */
    @PostMapping("/pollAndTranscode")
    public ResponseEntity<?> pollAndTranscode(){
        transcodingJob.pollAndTranscode();
        return ResponseEntity.ok().build();
    }

    /**
     * 获取视频播放地址
     */
    @GetMapping("/getPlayUrl")
    public ResponseEntity<String> getPlayUrl(@RequestParam("id") UUID id) throws Exception {
        String playUrl = videoService.getPlayUrl(id);
        return ResponseEntity.ok(playUrl);
    }

    /**
     * 分页获取视频列表
     */
    @GetMapping("/getVideos")
    public ResponseEntity<PageResult<Video>> getVideos(
            @RequestParam(value = "title",required = false) String title,
            @RequestParam(value = "page", defaultValue = "1") Integer page,
            @RequestParam(value = "size", defaultValue = "3") Integer size) {
        PageResult<Video> videos = videoService.getVideos(title, page, size);
        return ResponseEntity.ok(videos);
    }
}